/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.biz.service.impl;

import me.zhengjie.modules.biz.domain.Lab;
import me.zhengjie.modules.biz.domain.RefrigeratorLog;
import me.zhengjie.modules.biz.repository.LabRepository;
import me.zhengjie.modules.biz.service.dto.RefrigeratorDto;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.biz.repository.RefrigeratorLogRepository;
import me.zhengjie.modules.biz.service.RefrigeratorLogService;
import me.zhengjie.modules.biz.service.dto.RefrigeratorLogDto;
import me.zhengjie.modules.biz.service.dto.RefrigeratorLogQueryCriteria;
import me.zhengjie.modules.biz.service.mapstruct.RefrigeratorLogMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author Admin
* @date 2023-02-17
**/
@Service
@RequiredArgsConstructor
public class RefrigeratorLogServiceImpl implements RefrigeratorLogService {

    private final RefrigeratorLogRepository refrigeratorLogRepository;
    private final RefrigeratorLogMapper refrigeratorLogMapper;
    private final LabRepository labRepository;
    private final UserRepository userRepository;

    @Override
    public Map<String,Object> queryAll(RefrigeratorLogQueryCriteria criteria, Pageable pageable){
        Page<RefrigeratorLog> page = refrigeratorLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        Page<RefrigeratorLogDto> dto = page.map(refrigeratorLogMapper::toDto);
        List<RefrigeratorLogDto> resultDto = dto.getContent();
        for (RefrigeratorLogDto refrigeratorLogDto:resultDto) {
            if (refrigeratorLogDto.getLabId() != null) {
                Lab lab = labRepository.findById(refrigeratorLogDto.getLabId()).orElseGet(Lab::new);
                ValidationUtil.isNull( lab.getId(),"Lab","id",refrigeratorLogDto.getLabId());
                refrigeratorLogDto.setLabName(lab.getName());
            }
            if (refrigeratorLogDto.getAdministrator() != null) {
                User user = userRepository.findById(Long.valueOf(refrigeratorLogDto.getAdministrator())).orElseGet(User::new);
                ValidationUtil.isNull( user.getId(),"User","id",refrigeratorLogDto.getAdministrator());
                refrigeratorLogDto.setAdministratorName(user.getUsername());
            }
        }
        return PageUtil.toPage(dto);
    }

    @Override
    public List<RefrigeratorLogDto> queryAll(RefrigeratorLogQueryCriteria criteria){
        List<RefrigeratorLog> refrigeratorLogList = refrigeratorLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder));
        List<RefrigeratorLogDto> refrigeratorLogDtoList = refrigeratorLogMapper.toDto(refrigeratorLogList);
        for (RefrigeratorLogDto refrigeratorLogDto : refrigeratorLogDtoList) {
            if (refrigeratorLogDto.getLabId() != null) {
                Lab lab = labRepository.findById(refrigeratorLogDto.getLabId()).orElseGet(Lab::new);
                ValidationUtil.isNull( lab.getId(),"Lab","id",refrigeratorLogDto.getLabId());
                refrigeratorLogDto.setLabName(lab.getName());
            }
            if (refrigeratorLogDto.getAdministrator() != null) {
                User user = userRepository.findById(Long.valueOf(refrigeratorLogDto.getAdministrator())).orElseGet(User::new);
                ValidationUtil.isNull( user.getId(),"User","id",refrigeratorLogDto.getAdministrator());
                refrigeratorLogDto.setAdministratorName(user.getUsername());
            }
        }
        return refrigeratorLogDtoList;
    }

    @Override
    @Transactional
    public RefrigeratorLogDto findById(Integer id) {
        RefrigeratorLog refrigeratorLog = refrigeratorLogRepository.findById(id).orElseGet(RefrigeratorLog::new);
        ValidationUtil.isNull(refrigeratorLog.getId(),"RefrigeratorLog","id",id);
        return refrigeratorLogMapper.toDto(refrigeratorLog);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RefrigeratorLogDto create(RefrigeratorLog resources) {
        return refrigeratorLogMapper.toDto(refrigeratorLogRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(RefrigeratorLog resources) {
        RefrigeratorLog refrigeratorLog = refrigeratorLogRepository.findById(resources.getId()).orElseGet(RefrigeratorLog::new);
        ValidationUtil.isNull( refrigeratorLog.getId(),"RefrigeratorLog","id",resources.getId());
        refrigeratorLog.copy(resources);
        refrigeratorLogRepository.save(refrigeratorLog);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            refrigeratorLogRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<RefrigeratorLogDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (RefrigeratorLogDto refrigeratorLog : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("名称", refrigeratorLog.getName());
            map.put("实验室", refrigeratorLog.getLabName());
            map.put("负责人", refrigeratorLog.getAdministratorName());
            if (refrigeratorLog.getTemperature() != null) {
                map.put("温度", refrigeratorLog.getTemperature() + "℃");
            } else {
                map.put("温度", "--℃");
            }
            if (refrigeratorLog.getTemperatureThresholdValue() != null) {
                map.put("温度阈值", refrigeratorLog.getTemperatureThresholdValue() + "℃");
            } else {
                map.put("温度阈值", "--℃");
            }
            if (refrigeratorLog.getHumidity() != null) {
                map.put("湿度", refrigeratorLog.getHumidity() + "%");
            } else {
                map.put("湿度", "--%");
            }
            if (refrigeratorLog.getHumidityThresholdValue() != null) {
                map.put("湿度阈值", refrigeratorLog.getHumidityThresholdValue() + "%");
            } else {
                map.put("湿度阈值", "--%");
            }
            map.put("报警信息", refrigeratorLog.getErrorMessage());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public RefrigeratorLog createRefrigeratorLog(float humidity, float temperature) {
        RefrigeratorLog refrigeratorLog = new RefrigeratorLog();
        refrigeratorLog.setHumidity(humidity);
        refrigeratorLog.setTemperature(temperature);
        refrigeratorLog.setRefrigeratorId(1);
        refrigeratorLog = refrigeratorLogRepository.save(refrigeratorLog);
        return refrigeratorLog;
    }
}
